package com.bungarus.test;

import com.bungarus.client.busi.EndUser;
import com.bungarus.codec.protobuf.MessageProtobuf;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

abstract public class AbstractAccessTestClient  {
    protected EndUser loggedInUser;
    protected final static int PORT_9080 = 9080;

    private Bootstrap client;
    private Channel channel;

    private static SmartTestClient smartClient = new SmartTestClient();

    // main logic
    abstract void run(String accessPoint);

    public AbstractAccessTestClient(){
        client = new Bootstrap();
        client.group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new TestClientChannelInitializer(this));
    }

    /**
     * get input string from commandline
     * @return
     */
    public String getInputString(){
        String line = "";
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            line = reader.readLine();
        }catch(IOException e){
            e.printStackTrace();
        }
        return line;
    }

    /**
     * connect to target server
     */
    public void connectServer(String server){
        try {
//            boolean again = true;
//            do {
//                List<String> ipList = smartClient.getIpList();
//                if (ipList.size() > 0) {
//                    channel = client.connect(ipList.get(0), PORT_9080).sync().channel();
//                    again = false;
//                    break;
//                }
//                Thread.sleep(2000);
//            }while(again);
                    channel = client.connect(server, 9080).sync().channel();

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("Connect to Access failed!");
        }finally {

        }
    }

    /**
     * send message
     * @param message
     */
    public void send(MessageProtobuf.Message message){
        channel.writeAndFlush(message).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (channelFuture.isSuccess()) {
                    System.out.println("---------------------- client sent successfully!");
                }
            }
        });
    }

    public void setLoggedInUser(EndUser user){
        loggedInUser = user;
    }
}
